package org.example.exampreparationtreasure.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.exampreparationtreasure.common.CommonResultStatus;
import org.example.exampreparationtreasure.exception.UserException;
import org.example.exampreparationtreasure.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String headerName = jwtConfig.getHeader();
        String token = request.getHeader(headerName);

        if (token == null || token.isEmpty()) {
            throw new UserException(CommonResultStatus.UNAUTHORIZED, "未提供令牌");
        }

        try {
            if (jwtUtil.isTokenExpired(token)) {
                throw new UserException(CommonResultStatus.UNAUTHORIZED, "令牌已过期");
            }
        } catch (Exception e) {
            throw new UserException(CommonResultStatus.UNAUTHORIZED, "无效令牌");
        }

        return true;
    }
}


